#include "stdafx.h"

#include "Utilities.h"

namespace ETM
{
	namespace Utils
	{
		sf::IntRect GetSrcRect(int tilesetWidth, int tileSize, int index)
		{
			int tilesPerRow = tilesetWidth / tileSize;
			int x = (index % tilesPerRow) * tileSize;
			int y = (index / tilesPerRow) * tileSize;

			return sf::IntRect(x, y, x + tileSize, y + tileSize);
		}

		int GetRectIndex(int tilesetWidth, int tileSize, sf::IntRect rect)
		{
			int iX = rect.Left / tileSize;
			int iY = (rect.Top / tileSize) * (tilesetWidth / tileSize);

			return iX + iY;
		}

		sf::Vector2f SpriteCenter(sf::Sprite& sprite)
		{
			sf::Vector2f pos = sprite.GetPosition();
			sf::Vector2f size = sprite.GetSize();
			return sf::Vector2f(pos.x + size.x / 2, pos.y + size.y / 2);
		}

		void RenderShadowText(sf::RenderWindow& window, sf::String& string)
		{
			sf::Vector2f oldPos = string.GetPosition();
			sf::Color oldCol = string.GetColor();

			string.SetColor(sf::Color(0, 0, 0));
			string.SetPosition(oldPos.x + 1, oldPos.y + 1);
			window.Draw(string);

			string.SetColor(oldCol);
			string.SetPosition(oldPos);
			window.Draw(string);
		}

		sf::Vector2f GetIntersectionDepth(sf::FloatRect rectA, sf::FloatRect rectB)
		{
			float hWidthA = rectA.GetWidth() / 2.0f;
			float hHeightA = rectA.GetHeight() / 2.0f;
			float hWidthB = rectB.GetWidth() / 2.0f;
			float hHeightB = rectB.GetHeight() / 2.0f;

			sf::Vector2f cA = sf::Vector2f(rectA.Left + hWidthA, rectA.Top + hHeightA);
			sf::Vector2f cB = sf::Vector2f(rectB.Left + hWidthB, rectB.Top + hHeightB);

			float dX = cA.x - cB.x;
			float dY = cA.y - cB.y;
			float mdX = hWidthA + hWidthB;
			float mdY = hHeightA + hHeightB;

			if(abs(dX) >= mdX || abs(dY) >= mdY)
				return sf::Vector2f(0, 0);

			float depthX = dX > 0 ? mdX - dX : -mdX - dX;
			float depthY = dY > 0 ? mdY - dY : -mdY - dY;

			return sf::Vector2f(depthX, depthY);
		}
	}
}